package cn.ulc.common.gen;

import cn.hutool.core.util.StrUtil;
import org.beetl.sql.core.*;
import org.beetl.sql.core.annotatoin.Sql;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.core.db.TableDesc;
import org.beetl.sql.core.kit.GenKit;
import org.beetl.sql.ext.DebugInterceptor;
import org.beetl.sql.ext.gen.GenConfig;
import org.beetl.sql.ext.gen.MDCodeGen;

import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

public class genPoJo {


    public static void main (String[] args) {

        //生成全部代码
//        genCodeAll(sqlManager);

        //根据表生成PoJo实体及SQL.md
        new genPoJo().genCode("activity_goods","押金退款订单明细","cn.ulc", getSQLManager());

    }

    private SQLManager sqlManager;

    public void setSqlManager(SQLManager sqlManager) {
        SQLLoader loader = new ClasspathLoader("/sql");
        sqlManager.setSqlLoader(loader);
        this.sqlManager = sqlManager;
    }

    private static SQLManager getSQLManager() {
        MySqlStyle style = new MySqlStyle();
        ConnectionSource source = ConnectionSourceHelper.getSimple(MysqlDBConfig.driver, MysqlDBConfig.url, MysqlDBConfig.userName, MysqlDBConfig.password);
        SQLLoader loader = new ClasspathLoader("/sql");
        return new SQLManager(style, loader, source, new UnderlinedNameConversion(), new Interceptor[]{new DebugInterceptor()});
    }

    public void genCode(String tableName, String classTitle, String genPackageName, SQLManager sqlManager) {
        setSqlManager(sqlManager);
        //生成model\sql\dao
        genCodePoJoAndSql(tableName,genPackageName);
        //生成md
        genMd(tableName,genPackageName);
        //生成dto\params\services\controllers
        genCodeCommon(tableName, classTitle, genPackageName);
    }

    public  void genCodeCommon(String tableName,String classTitle,String genPackageName) {
        try {
            GenKit.setSrcPathRelativeToSrc("../app/socket/src/main/java");
            GenKit.setResourcePathRelativeToSrc("../app/socket/src/main/resources");
            //生成dto\param
            CommonCodeGen listDTOCodeGen = new CommonCodeGen(genPackageName+".socket.admin.model.dto","/gen/dto.list.btl","ListDTO");
            listDTOCodeGen.genCode(sqlManager,tableName,true);
            CommonCodeGen detailDTOCodeGen = new CommonCodeGen(genPackageName+".socket.admin.model.dto","/gen/dto.detail.btl","DTO");
            detailDTOCodeGen.genCode(sqlManager,tableName,true);
            CommonCodeGen listParamCodeGen = new CommonCodeGen(genPackageName+".socket.admin.model.param","/gen/param.list.btl","ListParam");
            listParamCodeGen.genCode(sqlManager,tableName,true);
            CommonCodeGen detailParamCodeGen = new CommonCodeGen(genPackageName+".socket.admin.model.param","/gen/param.detail.btl","Param");
            detailParamCodeGen.genCode(sqlManager,tableName,true);
            //生成service
            CommonCodeGen serviceCodeGen = new CommonCodeGen(genPackageName+".socket.admin.service","/gen/service.btl","Serv");
            serviceCodeGen.genCode(sqlManager,tableName);
            CommonCodeGen serviceImplCodeGen = new CommonCodeGen(genPackageName+".socket.admin.service.impl","/gen/service.impl.btl","ServImpl",classTitle);
            serviceImplCodeGen.genCode(sqlManager,tableName);
            //生成controller
            CommonCodeGen controllerGen = new CommonCodeGen(genPackageName+".socket.admin.controller","/gen/controller.btl","Ctrl",classTitle);
            controllerGen.genCode(sqlManager,tableName);

        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  void genMd(String tableName,String genPackageName) {
        TableDesc desc = sqlManager.getMetaDataManager().getTable(tableName);
        try {
            MDCodeGen mdCodeGen = new MDCodeGen();
            mdCodeGen.setMapperTemplate(new GenConfig().getTemplate("/gen/sql.md.btl"));
            String target = GenKit.getJavaResourcePath() + "/sql/" + StrUtil.toCamelCase(tableName) + ".md";
            FileWriter writer = new FileWriter(new File(target));
            mdCodeGen.genCode(sqlManager.getBeetl(),desc,sqlManager.getNc(),"m",writer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public  void genCodePoJoAndSql(String tableName,String genPackageName) {
        try {
            GenKit.setSrcPathRelativeToSrc("../store/src/main/java");
            GenKit.setResourcePathRelativeToSrc("../store/src/main/resources");
//            TableDesc desc = sqlManager.getMetaDataManager().getTable(tableName);
//            String entityClass = StrUtil.upperFirst(StrUtil.toCamelCase(tableName));
            //生成实体
            GenConfig config = new GenConfig("/gen/entity.btl");
            config.preferBigDecimal(true);
            config.setBaseClass("BaseModel");
            //生成Dao
            DaoCodeGen daoGen = new DaoCodeGen(genPackageName+".store.dao");
            daoGen.setMapperTemplate((new GenConfig("/gen/dao.btl")).getTemplate());
            config.codeGens.add(daoGen);
//            daoGen.genCode("cn.ulc.common.dao",entityClass,desc,null,false);

            if(StrUtil.isBlank(tableName)) {
                sqlManager.genALL(genPackageName+".store.entity", config, null);
            }else {
                sqlManager.genPojoCode(tableName, genPackageName+".store.entity",config);
                sqlManager.genSQLFile(tableName, config);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class MySqlConnectionSource implements ConnectionSource {
        @Override
        public Connection getMetaData() {
            return null;
        }

        public MySqlConnectionSource() {

        }

        private Connection _getConn(){
            String driver = MysqlDBConfig.driver;
            String dbName = MysqlDBConfig.dbName;
            String password = MysqlDBConfig.password;
            String userName = MysqlDBConfig.userName;
            String url = MysqlDBConfig.url;
            Connection conn = null;
            try {
                Class.forName(driver);
                conn = DriverManager.getConnection(url, userName,
                        password);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return conn;
        }

        public Connection getMaster() {
            return _getConn();
        }

        public Connection getConn(String sqlId, boolean isUpdate, String sql, List paras) {
            return _getConn();
        }



        public boolean isTransaction() {
            // TODO Auto-generated method stub
            return false;
        }

        public Connection getSlave() {
            return this.getMaster();
        }

        public void forceBegin(boolean isMaster) {
            // TODO Auto-generated method stub

        }

        public void forceEnd() {
            // TODO Auto-generated method stub

        }

//        @Override
//        public Connection getMetaData() {
//            // TODO Auto-generated method stub
//            return null;
//        }




    }

    static class MysqlDBConfig {
        public static String driver = "com.mysql.jdbc.Driver";
        public static String dbName = "single_shop";
        public static String password = "123456";
        public static String userName = "root";
        public static String url = "jdbc:mysql://127.0.0.1:3306/" + dbName+"?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8";

    }
}
